import { API_LOGIN } from "@/constants/api";
import Taro from "@tarojs/taro";
import { CustomRequest } from "./request";
// import { isFromCloud } from "./test";

export default class Auth {
  static appCheckSessionKey() {
    const That = this;
    Taro.checkSession({
      success: function () {
        //session_key 未过期，并且在本生命周期一直有效
        That.appWxLogin(); //重新登录
      },
      fail: function () {
        // Taro.clearStorageSync();
        // session_key 已经失效，需要重新执行登录流程
        That.appWxLogin(); //重新登录
      }
    });
  }

  static appWxLogin() {
    Taro.login({
      success: function (res) {
        if (res.code) {
          Taro.setStorageSync("code", res.code);
          //发起网络请求
          Taro.request({
            method: "POST",
            url: `${API_LOGIN}`,
            data: {
              jsCode: res.code
            },
            success: res => {
              const token = res.header.wxToken;
              if (res.data.code === "200000") {
                Taro.setStorageSync("token", token);
                Taro.setStorageSync("userInfo", res.data.data);
              }
            },
            fail: err => {
              console.log("err", err);
            }
          });
        }
      },
      fail: function (err) {
        console.log("err", err);
      }
    });
  }

  static gotoLogin() {
    //清除缓存
    // 登录
    Taro.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId

        if (res.code) {
          console.log(res);
        } else {
          console.log("登录失败！" + res.errMsg);
        }
      }
    });
  }

  static checkPhoneAuth() {
    Taro.getStorage({
      key: "userInfo",
      success: function (res) {
        if (!res.data.phone) {
          Taro.redirectTo({
            url: "/packages/package-user-login/user-login/index"
          });
        }
      },
      fail: () => {
        console.log("fail");
      }
    });
  }

  static getPhoneNumber(e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      CustomRequest.formDataPost("weChat/wx/decodePhone", {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        wxToken: Taro.getStorageSync("token"),
        address: Taro.getStorageSync("city")
          ? Taro.getStorageSync("city")
          : "未授权"
      })
        .then((res: any) => {
          if (res.id) {
            Taro.setStorageSync("userInfo", res);
            // Taro.switchTab({
            //   url: "/pages/index/index"
            // });
          }
        })
        .catch(_err => {
          Taro.showToast({
            title: "手机号授权失败,请稍后重试",
            icon: "none",
            duration: 2000
          });
        });
    }
  }
}